/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package aiaudio.processing.base.helpers.latex;

import java.io.BufferedWriter;
import static aiaudio.processing.base.helpers.latex.TexConstants.*;
import java.io.IOException;

/**
 *
 * @author nastya
 */
public class TexTableMaker {

    private BufferedWriter writer;
    private ITexableTable table;

    public TexTableMaker(BufferedWriter writer, ITexableTable table) {
        this.writer = writer;
        this.table = table;
    }

    public void write() throws IOException {
        String name = table.getName();
//        writer.write(name);
//        writer.write("\n");
        table.reset();        
        writer.write(TABLE_BEGIN_1);
        String columnsDescription = getColumnsDescriprion();
        writer.write(columnsDescription);
        writer.write(TABLE_BEGIN_2);
        writer.write(TABLE_CAPTION_1);
        writer.write(name);
        writer.write(TABLE_CAPTION_2);
        writeTableCaption();
        writer.write(TABLE_END_HEAD);
        writeTableBody();
        writer.write(TABLE_END);
        writer.write(NEW_PAGE);
    }

    private String getColumnsDescriprion() {
        return String.valueOf(table.getColumnCount());
    }

    private void writeTableCaption() throws IOException {
        for (int i = 0; i < table.getColumnCount(); i++) {
            if(i != 0){
                writer.write("&");
            }
            String columnDescription = table.getColumn(i);
            writer.write(columnDescription);
        }
        writer.write(" \\\\ " + TABLE_HLINE + "\n");
    }

    private void writeTableBody() throws IOException {
        table.start();
        
        while(table.moveNext()){
            writeTableRow();
        }
    }

    private void writeTableRow() throws IOException {
        for (int i = 0; i < table.getColumnCount(); i++) {
            if(i != 0){
                writer.write("&");
            }
            String value = table.getCurrentRowValue(i);
            writer.write(value);
        }
        writer.write(" \\\\ " + TABLE_HLINE + "\n");
    }
    
    public void close(){
        table.close();
    }
}
